import admin from '@/api/admin'
import { removeToken } from '@/utils/auth'
import Cookies from 'js-cookie'

const RECEIVE_USER_INFO = 'auth/RECEIVE_USER_INFO'
const UPDATE_USER_INFO = 'auth/UPDATE_USER_INFO'
const UPDATE_USER_INFO_POWER = 'auth/UPDATE_USER_INFO_POWER'

const state = {
  userInfo: null,
  menuTree: null,
  token: null
}

const getters = {
  userInfo: state => state.userInfo,
  menuTree: state => state.menuTree
}

const actions = {
  // 登录
  Login({ commit }, userInfo) {
    const username = userInfo.username.trim()
    return new Promise((resolve, reject) => {
      admin.login(username, userInfo.password).then(response => {
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 登出
  LogOut({ commit, state }) {
    return new Promise((resolve, reject) => {
      admin.logout(state.userInfo.uid).then(() => {
        removeToken()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  async fetchUserInfo({ commit, getters }) {
    try {
      const res = await admin.getInfo(Cookies.get('user_id'))
      commit(RECEIVE_USER_INFO, res)
      return Promise.resolve(res)
    } catch (err) {
      return Promise.reject(err)
    }
  },
  updateUserInfoAction(context, userData) {
    context.commit(UPDATE_USER_INFO, userData)
  },
  // 更新用户权限
  updateUserPower(context, data) {
    admin.getPower(state.userInfo.uid).then((data) => {
      context.commit(UPDATE_USER_INFO_POWER, data)
    })
  }
}

const mutations = {
  [RECEIVE_USER_INFO](state, data) {
    state.userInfo = data.data.userInfo
    state.menuTree = data.data.powerTree
    state.token = data.data.token
  },
  [UPDATE_USER_INFO](state, userInfo) {
    // 更新运行时用户信息
    for (const key in userInfo) {
      state.userInfo[key] = userInfo[key]
    }
  },
  // 更新用户权限
  [UPDATE_USER_INFO_POWER](state, data) {
    state.userInfo.power = data.data
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
